<template>
    <div class="min-h-screen flex flex-col">
        <!-- Header -->
        <header class="bg-blue-600 text-white p-4 shadow-md flex justify-center items-center">
            <div class="container mx-auto flex justify-center items-center">
                <div class="text-c" v-if="!username">
                    <button class="btn btn-primary" @click="$router.push('/register')">注册</button>
                    <button class="btn btn-primary" @click="$router.push('/login')">登录</button>
                </div>
                <div class="user-info" v-else>
                    <div class="user-info-wrapper">
                        <img :src="avatar" alt="用户头像" class="user-avatar" />
                        <span>{{ username }}</span>
                    </div>
                </div>
            </div>
        </header>

        <!-- Search -->
        <div class="search-header">
            <div class="search-wrapper">
                <h1 class="text-a">丁香医生</h1>
                <input type="text" v-model="searchQuery" placeholder="搜索疾病、医院、药品" class="search-input" />
                <button class="search-button">搜索</button>
            </div>
        </div>

        <!-- Navigation -->
        <nav class="main-nav">
            <router-link v-for="item in navigationItems" :key="item.name" :to="item.link" class="nav-link">
                {{ item.name }}
            </router-link>
        </nav>

        <!-- Breadcrumb Navigation -->
        <div class="breadcrumb-container mb-4">
            <nav class="flex items-center text-sm">
                <router-link to="/" class="text-emerald-500 hover:text-emerald-600">首页</router-link>
                <span class="mx-2 text-gray-400">›</span>
                <span class="text-gray-600">大家都在问</span>
            </nav>
        </div>

        <!-- Main Content -->
        <div class="qa-container">
            <div class="content-wrapper">
                <div class="categories-container">
                    <div class="category-box">
                        <div class="category-header">科室</div>
                        <div class="category-content">
                            <button v-for="dept in departments" :key="dept.id" @click="selectDepartment(dept)"
                                :class="['category-btn',selectedDepartment?.id === dept.id ? 'active' : '']">
                                {{ dept.name }}
                            </button>
                        </div>
                    </div>

                    <div class="category-box">
                        <div class="category-header">疾病</div>
                        <div class="category-content">
                            <button v-for="treatment in treatments" :key="treatment.id"
                                @click="selectTreatment(treatment)"
                                :class="['category-btn', selectedTreatment?.id === treatment.id ? 'active' : '']">
                                {{ treatment.name }}
                            </button>
                        </div>
                    </div>
                </div>

                <div class="main-content-area">
                    <div class="qa-list">
                        <div v-for="question in questions" :key="question.id" class="qa-card"
                            @click="navigateToQuestion(question.id)">
                            <div class="question-header">
                                <img :src="question.avatar" alt="User" />
                                <div>
                                    <p class="question-date">{{ new Date(question.created_time).toLocaleDateString() }}
                                    </p>
                                    <div class="question-content" v-html="question.content"></div>
                                </div>
                            </div>

                            <div v-if="question.answers && question.answers.length > 0" class="answer-container">
                                <img :src="question.answers[0].doctor.avatar" alt="Doctor" />
                                <div class="answer-content-wrapper">
                                    <div class="answer-doctor-info">
                                        <span class="doctor-name">{{ question.answers[0].doctor.name }}</span>
                                        <span class="doctor-title">{{ question.answers[0].doctor.get_title_display
                                            }}</span>
                                        <span class="doctor-department">| {{ question.answers[0].doctor.department
                                            }}</span>
                                        <span class="doctor-hospital">| {{ question.answers[0].doctor.hospital }}</span>
                                    </div>
                                    <div class="answer-content" v-html="question.answers[0].content"></div>
                                    <div class="help-count">帮助了 {{ question.answers[0].like_count }} 人</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="sidebar">
                        <div class="sidebar-box common-diseases">
                            <h3>常见疾病</h3>
                            <div class="disease-grid">
                                <button v-for="disease in commonDiseases.slice(0, 10)" :key="disease.id"
                                    @click="navigateToDisease(disease.id)" class="disease-btn">
                                    {{ disease.name }}
                                </button>
                            </div>
                        </div>

                        <div class="sidebar-box department-doctors">
                            <h3>科室医生</h3>
                            <div class="doctor-card" @click="navigateToDoctor(doctor.id)"
                                v-for="doctor in departmentDoctors" :key="doctor.id">
                                <img :src="doctor.avatar" alt="Doctor" class="doctor-avatar" />
                                <div class="doctor-info">
                                    <div class="doctor-name">{{ doctor.name }}</div>
                                    <div class="doctor-title-dept">
                                        {{ doctor.get_title_display }} {{ doctor.department }}
                                    </div>
                                    <div class="doctor-hospital">{{ doctor.hospital }}</div>
                                    <div class="doctor-stats">
                                        <span class="doctor-price">¥{{ doctor.consultation_price }}</span>
                                        <span class="doctor-rating">{{ doctor.rating }}分</span>
                                        <span class="doctor-consults">{{ doctor.consultation_count }}问答</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <footer class="mt-auto">
            <div class="bottom-links">
                <a target="_blank" href="http://www.dxy.cn/pages/copyright.html" rel="nofollow">版权声明</a>
                <a target="_blank" href="https://dxy.com/column/board" rel="nofollow">作者编委</a>
                <a target="_blank" href="https://ask.dxy.com/ama/index" rel="nofollow">丁香医生</a>
                <a href="mailto:doctor@dxy.com" rel="nofollow">投稿邮箱 doctor@dxy.com</a>
                <a target="_blank">客服电话：0571-22931767</a>
            </div>
        </footer>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const username = ref<string | null>(null);
const avatar = ref<string | null>(null);
const searchQuery = ref('');

const navigationItems = [
    { name: '问医生', link: '/sections' },
    { name: '查疾病', link: '/disease' },
    { name: '查药品', link: '/medicine' },
    { name: '查医院', link: '/hospital' },
    { name: '查检查/手术', link: '/examination' },
    { name: '查疫苗', link: '/vaccine' },
    { name: '急救指南', link: '/emergency' },
    { name: '测一测', link: '/test' },
    { name: '科普视频', link: '/videos' }
];

interface Department {
    id: number;
    name: string;
}

interface Treatment {
    id: number;
    name: string;
    department: string;
    remark: string;
}

interface Doctor {
    id: number;
    name: string;
    avatar: string;
    get_title_display: string;
    hospital: string;
    department: string;
    price: number;
    rating: number;
    consult_count: number;
}

interface Answer {
    id: number;
    content: string;
    created_time: string;
    doctor: Doctor;
    like_count: number;
}

interface Question {
    id: number;
    name: string;
    content: string;
    avatar: string;
    created_time: string;
    view_count: number;
    answers: Answer[];
}

const departments = ref<Department[]>([]);
const treatments = ref<Treatment[]>([]);
const questions = ref<Question[]>([]);
const commonDiseases = ref<Treatment[]>([]);
const departmentDoctors = ref<Doctor[]>([]);
const selectedDepartment = ref<Department | null>(null);
const selectedTreatment = ref<Treatment | null>(null);

const fetchUserInfo = async () => {
    const token = localStorage.getItem('token');
    if (token) {
        const payload = JSON.parse(atob(token.split('.')[1]));
        const userId = payload.id;

        const response = await fetch(`http://127.0.0.1:8000/user/userinfo/${userId}/`, {
            headers: { 'Authorization': `Bearer ${token}` }
        });
        const data = await response.json();
        username.value = data.username;
        avatar.value = data.avatar;
    }
};

const navigateToQuestion = (questionId: number) => {
    router.push(`/qa/${questionId}`);
};

const fetchDepartments = async () => {
    try {
        const response = await axios.get('http://127.0.0.1:8000/doctor/department/0/');
        departments.value = response.data;
        if (departments.value.length > 0) {
            selectDepartment(departments.value[0]);
        }
    } catch (error) {
        console.error('Error fetching departments:', error);
    }
};

const selectDepartment = async (department: Department) => {
    selectedDepartment.value = department;
    selectedTreatment.value = null;
    await Promise.all([
        fetchTreatments(department.id),
        fetchQuestions(department.id, 0),
        fetchDepartmentDoctors(department.id)
    ]);
};

const fetchTreatments = async (departmentId: number) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/treat/${departmentId}/`);
        treatments.value = response.data;
        commonDiseases.value = response.data.slice(0, 10);
    } catch (error) {
        console.error('Error fetching treatments:', error);
    }
};

const selectTreatment = async (treatment: Treatment) => {
    selectedTreatment.value = treatment;
    if (selectedDepartment.value) {
        await fetchQuestions(selectedDepartment.value.id, treatment.id);
    }
};

const fetchQuestions = async (departmentId: number, treatmentId: number) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/question/${departmentId}/${treatmentId}/`);
        questions.value = response.data.results;
    } catch (error) {
        console.error('Error fetching questions:', error);
    }
};

const fetchDepartmentDoctors = async (departmentId: number) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/doctor/${departmentId}/`);
        departmentDoctors.value = response.data.slice(0, 3);
    } catch (error) {
        console.error('Error fetching department doctors:', error);
    }
};

const navigateToDisease = (treatId: number) => {
    router.push(`/treat/${treatId}`);
};

const navigateToDoctor = (doctorId: number) => {
    router.push(`/doctor/${doctorId}`);
};

onMounted(() => {
    fetchDepartments();
    fetchUserInfo();
});
</script>

<style scoped>
.breadcrumb-container {
    max-width: 1000px;
    margin: 0 auto;
}

.breadcrumb-container nav .text-emerald-500 {
    transition: color 0.3s ease;
}

.breadcrumb-container nav .text-emerald-500:hover {
    color: #00b38a;
}

.qa-container {
    background-color: #f8f9fa;
    min-height: 100vh;
    padding: 24px 0;
}

.content-wrapper {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 20px;
}

.categories-container {
    margin-bottom: 32px;
}

.category-box {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 16px;
    padding: 20px;
}

.category-header {
    color: #333;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

.category-content {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.category-btn {
    padding: 6px 16px;
    background-color: #f5f5f5;
    border: none;
    border-radius: 4px;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    white-space: nowrap;
}

.category-btn:hover {
    background-color: #e6f7f4;
    color: #00b38a;
}

.category-btn.active {
    background-color: #00b38a;
    color: white;
}

.main-content-area {
    display: flex;
    gap: 24px;
    margin-top: 24px;
}

.qa-list {
    flex: 1;
}

.qa-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: box-shadow 0.2s;
}

.qa-card:hover {
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.question-header {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 16px;
}

.question-header img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.question-date {
    font-size: 12px;
    color: #999;
    margin-bottom: 4px;
}

.question-content {
    font-size: 14px;
    color: #333;
    line-height: 1.6;
}

.answer-container {
    display: flex;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid #eee;
}

.answer-container img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
}

.answer-content-wrapper {
    flex: 1;
}

.answer-doctor-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
}

.doctor-name {
    font-weight: 500;
    color: #333;
}

.doctor-title,
.doctor-department,
.doctor-hospital {
    color: #666;
    font-size: 14px;
}

.answer-content {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    margin-bottom: 8px;
}

.help-count {
    color: #00b38a;
    font-size: 14px;
}

.sidebar {
    width: 300px;
    flex-shrink: 0;
}

.sidebar-box {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.sidebar-box h3 {
    font-size: 18px;
    font-weight: 500;
    color: #333;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

.disease-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
}

.disease-btn {
    text-align: left;
    padding: 8px;
    color: #666;
    background: none;
    border: none;
    font-size: 14px;
    cursor: pointer;
    transition: color 0.2s;
}

.disease-btn:hover {
    color: #00b38a;
}

.doctor-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.doctor-card {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    cursor: pointer;
    padding: 12px;
    border-radius: 8px;
    transition: background-color 0.2s;
}

.doctor-card:hover {
    background-color: #f5f5f5;
}

.doctor-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
}

.doctor-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.doctor-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    line-height: 1.2;
}

.doctor-title-dept {
    font-size: 14px;
    color: #666;
    line-height: 1.2;
}

.doctor-hospital {
    font-size: 14px;
    color: #666;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.doctor-stats {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 2px;
}

.doctor-price {
    color: #00b38a;
    font-size: 14px;
    font-weight: 500;
}

.doctor-rating,
.doctor-consults {
    color: #666;
    font-size: 14px;
}

.bottom-links {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
    padding: 24px;
    background-color: #f5f5f5;
}

.bottom-links a {
    color: #666;
    text-decoration: none;
    padding: 4px 8px;
}

.bottom-links a:hover {
    color: #00b38a;
}

@media (max-width: 1200px) {
    .main-content-area {
        flex-direction: column;
    }

    .sidebar {
        width: 100%;
    }
}

.btn-primary {
    margin-right: 10px;
}

.text-c {
    display: flex;
    justify-content: flex-end;
    width: 100%;
}

.btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    background-color: #00b38a;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.btn:hover {
    background-color: #00a17d;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    cursor: pointer;
}

.user-info-wrapper {
    display: flex;
    align-items: center;
    gap: 10px;
}

.main-nav {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
    background-color: #fff;
    border-bottom: 1px solid #eee;
}

.nav-link {
    padding: 6px 16px;
    color: #666;
    text-decoration: none;
    font-size: 14px;
    transition: color 0.2s;
}

.nav-link:hover {
    color: #00b38a;
}

.search-header {
    background-color: #fff;
    padding: 20px 0;
}

.search-wrapper {
    max-width: 600px;
    margin: 0 auto;
    display: flex;
    gap: 10px;
}

.text-a {
    font-size: 32px;
    font-weight: 700;
    color: #00b38a;
    margin: 0 auto;
    letter-spacing: 1px;
}

.search-input {
    flex: 1;
    padding: 12px 20px;
    border: 2px solid #00b38a;
    border-radius: 24px;
    font-size: 16px;
    outline: none;
}

.search-button {
    padding: 12px 30px;
    background-color: #00b38a;
    color: white;
    border: none;
    border-radius: 24px;
    cursor: pointer;
    font-size: 16px;
}


</style>